package com.webserver.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * 请求对象
 * 该类的每一个实例用
 */
public class HttpServletRequest {
    //请求行相关信息
    private String method;//请求方式GET
    private String uri;//抽象路径/string/ds
    private String protocol;//协议版本HTTP/1.1

    //保存所有消息头,key:消息头的名字value：消息头对应的值
    private Map<String,String> headers = new HashMap<>();

    private Socket socket;
    public HttpServletRequest(Socket socket) throws IOException {
        this.socket = socket;
        //1.1解析请求行
        parseRequestLine();
        //1.2解析消息头
        parseHeaders();
        //1.3解析正文
        parseContent();
    }
        //解析请求
        private void parseRequestLine() throws IOException {
            String line = readLine();
            System.out.println("请求行内容" + line);


            String[] a = line.split("\\s");
            method = a[0];
            uri = a[1];
            protocol = a[2];
            System.out.println("method:" + method);
            System.out.println("uri:" + uri);
            System.out.println("protocol:" + protocol);

        }

    //解析消息头
    private void parseHeaders() throws IOException {
            while (true){
                String  line = readLine();
                if(line.isEmpty()){
                    break;
                }
                System.out.println("消息头"+line);
                //将消息头按照冒号空格拆分为消息头的名字和值并以key,value形式存入headers
                String[] i = line.split("\\s");
                headers.put(i[0],i[1]);
                System.out.println("消息头："+line);
            }
            System.out.println("headers:"+headers);
        }


    //解析消息正文
    private void parseContent(){

    }
    private String readLine() throws IOException {
        InputStream in = socket.getInputStream();
        int d;
        StringBuilder builder = new StringBuilder();
        char cur = 'a', pre = 'a';
        while ((d = in.read())!=-1){
            cur = (char)d;
            if(pre == 13 && cur == 10){
                break;
            }
            builder.append(cur);
            pre = cur;
        }
        return builder.toString().trim();
    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getHeader(String name){
        return headers.get(name);
    }
}
